<?php

namespace App\Http\Controllers\Admin;


use App\Model\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;

class UserController extends BaseController{

    //用户


    //用户列表
    public function index(Request $request){

        $method=$request->method();
        if ($method=='POST'){
            $data=$request->all();
            Session::put('data',$data);
            $list=DB::table('user')->orderBy('create_time','desc')->paginate(15);

            if(!is_null($data['nickName'])){
                $where[] = ['nickName','like','%'.trim($data['nickName']).'%'];
                $list=User::where($where)->orderBy('create_time','desc')->paginate(15);
            }

            if(!is_null($data['start']) && !is_null($data['end']) && !is_null($data['nickName'])){
                $where[] = ['nickName','like','%'.trim($data['nickName']).'%'];
                $list=DB::table('user')->where($where)->whereBetween('create_time',[strtotime($data['start']),strtotime($data['end'])])->orderBy('create_time','desc')->paginate(15);

            }

                  if(!is_null($data['start']) && !is_null($data['end'])){
                $where[] = ['nickName','like','%'.trim($data['nickName']).'%'];
                $list=DB::table('user')->where($where)->whereBetween('create_time',[strtotime($data['start']),strtotime($data['end'])])->orderBy('create_time','desc')->paginate(15);

            }

        }else{
            $list=DB::table('user')->orderBy('create_time','desc')->paginate(15);
            $data['nickName']='';
            $data['start']='';
            $data['end']='';
            Session::put('data',$data);
        }

        foreach ($list as $k=>$v){
        	$list[$k]->amount=$this->amount($v->user_id);
        }

        return view('user.index',compact('list'));
    }


  //累计消费总额
   public function amount($user_id){
   	 return DB::table('order')->where('user_id',$user_id)->sum('pay_price');
   }



    //删除
    public function del(Request $request){
        $user_id=(int)($request->input('user_id'));
        $res=User::destroy($user_id);
        if ($res){
            $data=['code'=>1,'msg'=>'删除成功'];
        }else{
            $data=['code'=>0,'msg'=>'删除失败'];
        }
        return json_encode($data);
    }



}
